{% extends "base.html" %}

{% block content %}
<div class="container-fluid mt-4">
    <!-- 统计信息卡片 -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card text-white bg-primary">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title">总设备数</h6>
                            <h2 class="mb-0">{{ total_count }}</h2>
                        </div>
                        <i class="bi bi-pc-display" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card text-white bg-success">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title">在线设备</h6>
                            <h2 class="mb-0">{{ online_count }}</h2>
                        </div>
                        <i class="bi bi-check-circle" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card text-white bg-danger">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-title">告警设备</h6>
                            <h2 class="mb-0">{{ alert_count }}</h2>
                        </div>
                        <i class="bi bi-exclamation-triangle" style="font-size: 2rem;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="card mb-4">
        <div class="card-header bg-light">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">网络设备列表</h5>
                <div>
                    <a href="{{ url_for('topology') }}" class="btn btn-info btn-sm me-2">
                        <i class="bi bi-sitemap"></i> 网络拓扑
                    </a>
                    <a href="{{ url_for('add_device') }}" class="btn btn-primary btn-sm">
                        <i class="bi bi-plus-circle"></i> 添加设备
                    </a>
                    <button class="btn btn-outline-secondary btn-sm ms-2" onclick="refreshDevices()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新
                    </button>
                </div>
            </div>
        </div>

        <!-- 设备表格 -->
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>设备名称</th>
                            <th>IP地址</th>
                            <th>状态</th>
                            <th>CPU负载</th>
                            <th>最后在线</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for device in devices %}
                        <tr>
                            <td>
                                <i class="bi 
                                    {% if device.device_type == 'router' %}bi-router
                                    {% elif device.device_type == 'switch' %}bi-hdd-stack
                                    {% elif device.device_type == 'firewall' %}bi-shield-lock
                                    {% else %}bi-pc{% endif %}"></i>
                                {{ device.name }}
                            </td>
                            <td>{{ device.ip }}</td>
                            <td>
                                <span
                                    class="badge bg-{% if device.status == '在线' %}success{% else %}secondary{% endif %}">
                                    {{ device.status }}
                                </span>
                            </td>
                            <td>
                                {% if device.cpu_usage and device.cpu_usage > 0 %}
                                <div class="progress" style="height: 20px;">
                                    <div class="progress-bar 
                                        {% if device.cpu_usage > 90 %}bg-danger
                                        {% elif device.cpu_usage > 70 %}bg-warning
                                        {% else %}bg-success{% endif %}" role="progressbar"
                                        style="width: {{ device.cpu_usage }}%" aria-valuenow="{{ device.cpu_usage }}"
                                        aria-valuemin="0" aria-valuemax="100">
                                        {{ device.cpu_usage }}%
                                    </div>
                                </div>
                                {% else %}
                                <span class="text-muted">N/A</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if device.last_seen %}
                                {{ device.last_seen.strftime('%Y-%m-%d %H:%M') }}
                                {% else %}
                                <span class="text-muted">从未在线</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="{{ url_for('edit_device', id=device.id) }}"
                                        class="btn btn-outline-primary">
                                        <i class="bi bi-pencil-square"></i> 操作
                                    </a>
                                    <a href="{{ url_for('network_report', device_id=device.id) }}"
                                        class="btn btn-outline-info">
                                        <i class="bi bi-diagram-3"></i> 查看网络
                                    </a>
                                    <button class="btn btn-outline-danger"
                                        onclick="confirmDelete({{ device.id }}, '{{ device.name }}')">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 设备状态图表 -->
    <div class="card mb-4">
        <div class="card-header bg-light">
            <h5 class="mb-0">设备状态监控</h5>
        </div>
        <div class="card-body">
            <div id="statusChart" style="height: 300px;"></div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">确认删除设备</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除设备 <strong id="deviceNameToDelete"></strong> 吗？此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <a id="confirmDeleteBtn" href="#" class="btn btn-danger">确认删除</a>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript 部分 -->
    {% block scripts %}
    <!-- ECharts 图表库 -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.3.2/dist/echarts.min.js"></script>

    <script>
        let topo_routing_table = {};
        // 设备删除确认
        function confirmDelete(deviceId, deviceName) {
            const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            document.getElementById('deviceNameToDelete').textContent = deviceName;
            document.getElementById('confirmDeleteBtn').href = `/delete/${deviceId}`;
            modal.show();
        }

        // 刷新设备列表
        function refreshDevices() {
            const btn = document.querySelector('button[onclick="refreshDevices()"]');
            btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 刷新中...';

            fetch('/update')
                .then(response => {
                    if (response.ok) {
                        window.location.reload();
                    } else {
                        alert('刷新失败');
                        btn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 刷新';
                    }
                });
        }

        function refreshDRT() {
            fetch('/topology')
                .then(response => {
                    if (response.ok) {
                        window.location.reload();
                    } else {
                        alert('刷新失败');
                        btn.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 刷新';
                    }
                });
        }

        function parseTopology() {
            const nodes = []; // 节点集合
            const links = []; // 连接集合

            // 验证数据是否存在
            if (!devices || typeof devices !== 'object' || Object.keys(devices).length === 0) {
                throw new Error("设备数据为空或格式不正确");
            }

            console.log("开始解析拓扑数据");
            updateDebugInfo("开始解析拓扑数据");

            // 为每个设备创建节点
            Object.entries(devices).forEach(([deviceName, routes]) => {
                if (!routes || !Array.isArray(routes) || routes.length === 0) {
                    console.warn(`设备 ${deviceName} 的路由数据为空`);
                    return;
                }

                nodes.push({
                    name: deviceName,
                    symbol: 'rect',
                    symbolSize: [100, 50],
                    label: {
                        show: true,
                        position: 'top',
                        textStyle: { fontWeight: 'bold', fontSize: 14 }
                    },
                    itemStyle: { color: '#3399FF' },
                    type: 'device'
                });

                // 提取该设备的接口 IP
                const deviceInterfaces = routes
                    .filter(route => {
                        return route.interface &&
                            route.interface.startsWith('Vlanif') &&
                            route.mask &&
                            parseInt(route.mask) === 32 &&
                            route.network &&
                            route.nexthop;
                    })
                    .map(route => ({
                        ip: route.network,
                        interface: route.interface,
                        vlan: route.vlan_id || 'N/A',
                        device: deviceName,
                        nexthop: route.nexthop
                    }));

                console.log(`${deviceName} 找到 ${deviceInterfaces.length} 个有效接口`);
                updateDebugInfo(`${deviceName} 找到 ${deviceInterfaces.length} 个有效接口`);

                // 为每个接口创建节点并连接到设备
                deviceInterfaces.forEach(iface => {
                    nodes.push({
                        name: iface.ip,
                        symbol: 'circle',
                        symbolSize: 30,
                        label: {
                            show: true,
                            position: 'right',
                            formatter: `${iface.interface}\n${iface.ip}`
                        },
                        itemStyle: { color: '#409EFF' },
                        type: 'interface',
                        device: deviceName,
                        vlan: iface.vlan,
                        nexthop: iface.nexthop
                    });

                    links.push({
                        source: deviceName,
                        target: iface.ip,
                        lineStyle: { color: '#909399', width: 2 }
                    });
                });
            });

            // 查找设备间的连接关系
            nodes.forEach(node => {
                if (node.type !== 'interface') return;

                const targetNode = nodes.find(
                    target => target.type === 'interface' &&
                        target.name === node.nexthop &&
                        target.device !== node.device
                );

                if (targetNode) {
                    links.push({
                        source: node.name,
                        target: targetNode.name,
                        label: {
                            show: true,
                            position: 'middle',
                            formatter: `VLAN ${node.vlan}`
                        },
                        lineStyle: {
                            color: '#666',
                            width: 2,
                            curveness: 0.2
                        },
                        symbol: ['none', 'arrow']
                    });
                }
            });

            console.log("拓扑解析完成: 节点数=" + nodes.length + ", 连接数=" + links.length);
            updateDebugInfo("拓扑解析完成: 节点数=" + nodes.length + ", 连接数=" + links.length);

            return { nodes, links };
        }

        // 初始化状态图表
        function initStatusChart() {
            const chart = echarts.init(document.getElementById('statusChart'));
            console.log("ec 初始化完成")

            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    top: '5%',
                    left: 'center'
                },
                series: [
                    {
                        name: '设备状态',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '18',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            { value: {{ online_count }}, name: '在线设备', itemStyle: { color: '#28a745' } },
                            { value: {{ total_count - online_count }}, name: '离线设备', itemStyle: { color: '#6c757d' } },
                            { value: {{ alert_count }}, name: '告警设备', itemStyle: { color: '#dc3545' } }
                ]
            }
        ]
    };

        chart.setOption(option);
        window.addEventListener('resize', function () {
            chart.resize();
        });
}

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            initStatusChart();
        });
    </script>

    <style>
        /* 自定义样式 */
        .table-responsive {
            border-radius: 0.5rem;
            overflow: hidden;
        }

        .table th {
            white-space: nowrap;
        }

        .progress {
            min-width: 100px;
        }

        #statusChart {
            min-height: 300px;
        }
    </style>
    {% endblock %}
    {% endblock %}